package com.example.yunpicture.service.impl;

import cn.hutool.core.collection.CollUtil;
import cn.hutool.core.util.ObjUtil;
import cn.hutool.core.util.StrUtil;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.example.yunpicture.exception.BusinessException;
import com.example.yunpicture.exception.ErrorCode;
import com.example.yunpicture.exception.ThrowUtils;
import com.example.yunpicture.mapper.SpaceMapper;
import com.example.yunpicture.model.dto.space.SpaceAddRequest;
import com.example.yunpicture.model.dto.space.SpaceQueryRequest;
import com.example.yunpicture.model.entity.Space;
import com.example.yunpicture.model.entity.SpaceUser;
import com.example.yunpicture.model.entity.User;
import com.example.yunpicture.model.enums.SpaceLevelEnum;
import com.example.yunpicture.model.enums.SpaceRoleEnum;
import com.example.yunpicture.model.enums.SpaceTypeEnum;

import com.example.yunpicture.model.vo.SpaceVO;
import com.example.yunpicture.model.vo.UserVO;
import com.example.yunpicture.service.SpaceService;
import com.example.yunpicture.service.SpaceUserService;
import com.example.yunpicture.service.UserService;
import org.springframework.beans.BeanUtils;
import org.springframework.context.annotation.Lazy;
import org.springframework.stereotype.Service;
import org.springframework.transaction.support.TransactionTemplate;

import javax.annotation.Resource;
import java.util.List;
import java.util.Optional;
import java.util.stream.Collectors;

/**
 * @author LenoVO
 * @description 针对表【space(空间)】的数据库操作Service实现
 * @createDate 2025-03-26 15:52:02
 */
@Service
public class SpaceServiceImpl extends ServiceImpl<SpaceMapper, Space>
        implements SpaceService {

    @Resource
    private UserService userService;

    @Resource
    private TransactionTemplate transactionTemplate;

    @Resource
    @Lazy
    private SpaceUserService spaceUserService;

    /**
     * 获取封装后的空间信息
     *
     * @param space
     * @return
     */
    @Override
    public SpaceVO getSpaceVO(Space space) {
        //对象转封装类
        SpaceVO spaceVO = SpaceVO.objToVo(space);
        //关联查询用户信息（封装）
        Long userId = space.getUserId();
        if (userId != null && userId > 0) {
            User user = userService.getById(userId);
            //对象转封装类
            UserVO userVO = userService.getUserVO(user);
            spaceVO.setUser(userVO);
        }
        return spaceVO;
    }

    /**
     * 分页获取封装后的空间信息
     *
     * @param spacePage
     * @return
     */
    @Override
    public Page<SpaceVO> getSpaceVOPage(Page<Space> spacePage) {
        List<Space> spaceList = spacePage.getRecords();
        Page<SpaceVO> spaceVOPage = new Page<>(spacePage.getCurrent(), spacePage.getSize(), spacePage.getTotal());
        if (CollUtil.isEmpty(spaceList)) {
            return spaceVOPage;
        }
        //将对象列表转为封装列表
        List<SpaceVO> spaceVOList = spaceList.stream()
                .map(SpaceVO::objToVo)
                .collect(Collectors.toList());
        //关联查询userVO
        for (SpaceVO spaceVO : spaceVOList) {
            User user = userService.getById(spaceVO.getUserId());
            UserVO userVO = userService.getUserVO(user);
            spaceVO.setUser(userVO);
        }
        spaceVOPage.setRecords(spaceVOList);
        return spaceVOPage;
    }

    /**
     * 创建空间
     *
     * @param spaceAddRequest
     * @param loginUser
     * @return
     */
    @Override
    public long addSpace(SpaceAddRequest spaceAddRequest, User loginUser) {
        if (spaceAddRequest.getSpaceName() == null) {
            spaceAddRequest.setSpaceName("默认空间");
        }
        if (spaceAddRequest.getSpaceLevel() == null) {
            //默认是普通版
            spaceAddRequest.setSpaceLevel(SpaceLevelEnum.COMMON.getValue());
        }
        if (spaceAddRequest.getSpaceType() == null) {
            //默认创建私有空间
            spaceAddRequest.setSpaceType(SpaceTypeEnum.PRIVATE.getValue());
        }
        //dto转实体类
        Space space = new Space();
        BeanUtils.copyProperties(spaceAddRequest, space);
        //1.填充级别相关参数
        this.fillSpaceBySpaceLevel(space);
        //2.校验空间
        this.validSpace(space, true);
        //3.权限校验
        Long userId = loginUser.getId();
        space.setUserId(userId);
        if (SpaceLevelEnum.COMMON.getValue() != space.getSpaceLevel() && userService.isAdmin(loginUser)) {
            throw new BusinessException(ErrorCode.NO_AUTH_ERROR, "权限不足");
        }
        //4.一个用户只能创建一个空间
        //锁
        String lock = String.valueOf(userId).intern();
        synchronized (lock) {
            Long newSpaceId = transactionTemplate.execute(status -> {
                //判断是否已有空间
                boolean exists = this.lambdaQuery()
                        .eq(Space::getUserId, userId)
                        .eq(Space::getSpaceType,spaceAddRequest.getSpaceType())
                        .exists();
                ThrowUtils.throwif(exists, ErrorCode.OPERATION_ERROR, "每个用户每类空间只能创建一个");
                //操作数据库
                boolean result = this.save(space);
                ThrowUtils.throwif(!result, ErrorCode.OPERATION_ERROR);
                // 如果是团队空间，关联新增团队成员记录
                if (SpaceTypeEnum.TEAM.getValue() == spaceAddRequest.getSpaceType()) {
                    SpaceUser spaceUser = new SpaceUser();
                    spaceUser.setSpaceId(space.getId());
                    spaceUser.setUserId(userId);
                    spaceUser.setSpaceRole(SpaceRoleEnum.ADMIN.getValue());
                    result = spaceUserService.save(spaceUser);
                    ThrowUtils.throwif(!result, ErrorCode.OPERATION_ERROR, "创建团队成员记录失败");
                }
                //成功，返回空间id
                return space.getId();
            });
            return Optional.ofNullable(newSpaceId).orElse(-1L);
        }

    }

    /**
     * 查询条件
     *
     * @param spaceQueryRequest
     * @return
     */
    @Override
    public QueryWrapper<Space> getQueryWrapper(SpaceQueryRequest spaceQueryRequest) {
        QueryWrapper<Space> queryWrapper = new QueryWrapper<>();
        if (spaceQueryRequest == null) {
            return queryWrapper;
        }
        Long id = spaceQueryRequest.getId();
        String spaceName = spaceQueryRequest.getSpaceName();
        Integer spaceLevel = spaceQueryRequest.getSpaceLevel();
        Long userId = spaceQueryRequest.getUserId();
        String sortField = spaceQueryRequest.getSortField();
        String sortOrder = spaceQueryRequest.getSortOrder();
        Integer spaceType = spaceQueryRequest.getSpaceType();

        //组合
        queryWrapper.eq(ObjUtil.isNotEmpty(id), "id", id);
        queryWrapper.like(StrUtil.isNotEmpty(spaceName), "space_name", spaceName);
        queryWrapper.eq(ObjUtil.isNotEmpty(spaceLevel), "space_level", spaceLevel);
        queryWrapper.eq(ObjUtil.isNotEmpty(userId), "user_id", userId);
        queryWrapper.eq(ObjUtil.isNotEmpty(spaceType), "space_type", spaceType);
        //排序
        //queryWrapper.orderBy(StrUtil.isNotEmpty(sortField), sortOrder.equals("ascend"), sortField);
        return queryWrapper;
    }

    /**
     * 校验空间
     *
     * @param space
     */
    @Override
    public void validSpace(Space space, Boolean add) {
        ThrowUtils.throwif(space == null, ErrorCode.NOT_FOUND_ERROR);
        //1.取出要校验的参数
        String spaceName = space.getSpaceName();
        Integer spaceLevel = space.getSpaceLevel();
        SpaceLevelEnum levelEnum = SpaceLevelEnum.getEnumByValue(spaceLevel);
        Integer spaceType = space.getSpaceType();
        SpaceTypeEnum typeEnum = SpaceTypeEnum.getEnumByValue(spaceType);
        //2.判断是新增还是修改
        if (add) {
            //若是新增
            //校验name
            ThrowUtils.throwif(spaceName == null, ErrorCode.PARAMS_ERROR, "空间名称不能为空");
            //校验level
            ThrowUtils.throwif(spaceLevel == null, ErrorCode.PARAMS_ERROR, "空间级别不能为空");
            //校验spaceType
            ThrowUtils.throwif(spaceType == null, ErrorCode.PARAMS_ERROR, "空间类型不能为空");
        }
        //3.校验name和level
        ThrowUtils.throwif(spaceName.length() > 30, ErrorCode.PARAMS_ERROR, "空间名称过长");
        ThrowUtils.throwif(spaceLevel != null && levelEnum == null, ErrorCode.PARAMS_ERROR, "空间级别错误");
        ThrowUtils.throwif(spaceType != null && typeEnum == null, ErrorCode.PARAMS_ERROR, "空间类型错误");
    }

    /**
     * 初始空间级别大小
     * @param space
     */
    @Override
    public void fillSpaceBySpaceLevel(Space space) {
        SpaceLevelEnum enumByValue = SpaceLevelEnum.getEnumByValue(space.getSpaceLevel());
        if (enumByValue != null) {
            //设置图片总大小
            long maxSize = enumByValue.getMaxSize();
            if (space.getMaxSize() == null) {
                //如果原本没有设置图片总大小
                space.setMaxSize(maxSize);
            }
            //设置图片总数量
            long maxCount = enumByValue.getMaxCount();
            if (space.getMaxCount() == null) {
                //如果原本没有设置图片总数量
                space.setMaxCount(maxCount);
            }
        }
    }

    /**
     * 校验是否有空间权限
     *
     * @param space
     * @param loginUser
     */
    @Override
    public void checkSpaceAuth(Space space, User loginUser) {
        if (!loginUser.getId().equals(space.getUserId())) {
            throw new BusinessException(ErrorCode.NO_AUTH_ERROR, "没有空间权限");
        }
    }
}
